from collections import OrderedDict

from django.core.paginator import InvalidPage
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination as BasePagination


class PageNumberPagination(BasePagination):
    page_size = None
    max_page_size = 100000
    page_query_param = 'page'
    page_size_query_param = 'page_size'

    def get_paginated_response(self, data):
        return Response(OrderedDict([
            ('success', True),
            ('msg', ''),
            ('code', 200),
            ('total', self.page.paginator.count),
            ('data', data)
        ]))

    def paginate_queryset(self, queryset, request, view=None):
        """
        Paginate a queryset if required, either returning a
        page object, or `None` if pagination is not configured for this view.
        """
        if view:
            if hasattr(view, "page_query_param"):
                self.page_query_param = view.page_query_param

            if hasattr(view, "page_size_query_param"):
                self.page_size_query_param = view.page_size_query_param

        page_size = self.get_page_size(request)
        if not page_size:
            return None

        paginator = self.django_paginator_class(queryset, page_size)
        page_number = self.get_page_number(request, paginator)

        try:
            self.page = paginator.page(page_number)
        except InvalidPage:
            self.page = paginator.page(1)

        if paginator.num_pages > 1 and self.template is not None:
            # The browsable API should display pagination controls.
            self.display_page_controls = True

        self.request = request
        return list(self.page)
